from django.db import models


class Author(models.Model):
    """作者模型"""
    name = models.CharField(max_length=100)
    age = models.IntegerField()
    email = models.EmailField()

    def __str__(self):
        return '<Author(name=%s, age=%s, email=%s)>' % (self.name, self.age, self.email)

    class Meta:
        db_table = 'author'


class Publisher(models.Model):
    """出版社模型"""
    name = models.CharField(max_length=300)

    class Meta:
        db_table = 'publisher'


class Book(models.Model):
    """图书模型"""
    name = models.CharField(max_length=300)
    pages = models.IntegerField()
    price = models.FloatField()
    rating = models.FloatField()
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publisher = models.ForeignKey(Publisher, on_delete=models.CASCADE)

    def __str__(self):
        return '<Book(id=%s, name=%s, price=%s, rating=%s)>' % (self.id, self.name, self.price, self.rating)

    class Meta:
        db_table = 'book'


class BookOrder(models.Model):
    """图书订单模型"""
    book = models.ForeignKey("Book", on_delete=models.CASCADE, related_name='bookorders')
    price = models.FloatField()
    create_time = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return '<BookOrder(id=%s, book_id=%s, price=%s, create_time=%s)>' % (self.id, self.book_id, self.price,
                                                                             self.create_time)

    class Meta:
        db_table = 'book_order'
        # TODO: 设置在提取数据的排序方式
        ordering = ['-create_time', '-price']
